from al_earth.main.plugins import GenericEventLoader, Item
from dateutil import rrule
import feedparser

class EventLoader(GenericEventLoader):
    event_type = "RssFeed"
    def __init__(self,config):
        GenericEventLoader.__init__(self,config)
        self.recursion = rrule.rrule(rrule.SECONDLY, interval=self.config['interval'])
        try:
            self.cache=self.getData()
        except:
            pass
    def getData(self):
        newFeed=feedparser.parse(self.config['url'])
        if newFeed.bozo:
            self.status = "Error reading Rss-Feed"
            raise
        else:
            self.status = ""
        self.title=newFeed.feed.get('title', 'No title')
        return dict([(entry.link,
                      Item(entry.title,entry.description,self.title,entry.date))
                      for entry in newFeed.entries])
    def getItems(self):
        items = self.getData()
        newitems = set(items) - set(self.cache)
        if newitems:
            self.cache = items
            return [items[ni] for ni in newitems]
        return []
                
            
